package com.lambkit.plugin.ehcache;

import cn.hutool.core.util.StrUtil;
import com.jfinal.plugin.ehcache.EhCachePlugin;
import com.lambkit.core.Lambkit;
import com.lambkit.core.LifecycleException;
import com.lambkit.core.plugin.Plugin;
import net.sf.ehcache.config.Configuration;
import net.sf.ehcache.config.ConfigurationFactory;
import net.sf.ehcache.config.DiskStoreConfiguration;

import java.io.File;

/**
 * @author yangyong(孤竹行)
 */
public class EhcachePlugin extends Plugin {

    private EhCachePlugin ehCachePlugin;

    @Override
    public void start() throws LifecycleException {
        EhcacheConfig ehc = Lambkit.config(EhcacheConfig.class);
        if(StrUtil.isNotBlank(ehc.getPath())) {
            String ehcacheDiskStorePath = ehc.getPath();
            if("webrootpath".equalsIgnoreCase(ehc.getPath())){
                ehcacheDiskStorePath = Lambkit.context().resourceService().getWebRootPath(Lambkit.app().context().getResourcePathType());
            } else if("classpath".equalsIgnoreCase(ehc.getPath())) {
                ehcacheDiskStorePath = Lambkit.context().resourceService().getRootClassPath(Lambkit.app().context().getResourcePathType());
            }
            File pathFile = new File(ehcacheDiskStorePath, ".ehcache");
            System.out.println(pathFile);
            Configuration cfg = ConfigurationFactory.parseConfiguration();
            cfg.addDiskStore(new DiskStoreConfiguration().path(pathFile.getAbsolutePath()));

            ehCachePlugin = new EhCachePlugin(cfg);
        } else {
            ehCachePlugin = new EhCachePlugin();
        }
        ehCachePlugin.start();
        //return new EhCachePlugin(ehcacheDiskStorePath + File.separator + "ehcache.xml");
    }

    @Override
    public void stop() throws LifecycleException {
        super.stop();
        ehCachePlugin.stop();
    }
}
